import { initTrace } from './../ecjrts/tools/initTrace';
import { createWosaModule } from "./createMod";
import configs from "@/configs/device.config";
import { ref } from "vue";
import { link } from "@/ecjrts/tools/channelLinker";
import { BaseIO } from "@/ecjrts/mode/baseIO";


interface OpenAllDeviceResult {
  deviceName: string;
  result: string;
}

export let modsResult = ref<OpenAllDeviceResult[]>([]);
export const openAllDevice = async function (qObjects: any) {
  modsResult.value = [];
  let instances = createWosaModule(qObjects);


  for (const config of configs) {
    let currentResult = {
      deviceName: config.deviceName,
      result: "loading",
    };
    let instance = instances[config.deviceName];
    if (instance === undefined) {
      throw new Error(`not found mode "${config.deviceName}"`);
    }
    modsResult.value.push(currentResult);
    let result = modsResult.value[modsResult.value.length - 1];
    if (instance instanceof BaseIO) {
      let ret = await instance.Open(config.logicName, config.timeout);
      console.log(config.deviceName, ret.ret);
      if (ret.ret === "ConnectionOpened" || ret.ret === "OpenCompleted") {
        result.result = "ok";
      } else {
        result.result = "fail";
      }
    }
  }
};

export const initDevice = async () => {
  return new Promise((resolve, reject) => {
    link(undefined, (error) => {
      reject(error)
    }).then(qObjects => {
      initTrace(qObjects.trc);
      return openAllDevice(qObjects);
    }).then(() => {
      resolve('');
    }).catch(reason => {
      reject(reason)
    });
  })
};
